package cn.iocoder.yudao.module.product.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import static org.apache.commons.codec.digest.HmacUtils.hmacSha256;

/**
 * 百度文档翻译api
 *
 * @author Steven
 */
public class TranslateUtil {
    private String appid;
    private String seckey;
    private RestTemplate restTemplate = new RestTemplate();

    public TranslateUtil(String appid, String seckey) {
        this.appid = appid;
        this.seckey = seckey;
    }

    public String createQuoteJob(String fromLang, String toLang, String extend, String fileName, String filePath) throws IOException {
        String url = "https://fanyi-api.baidu.com/transapi/doctrans/createjob/quote";
        byte[] contentBytes = restTemplate.getForObject(filePath, byte[].class);
        String content = Base64.getEncoder().encodeToString(contentBytes);

        Map<String, Object> input = new HashMap<>();
        input.put("content", content);
        input.put("format", extend);
        input.put("filename", fileName);

        Map<String, Object> inputData = new HashMap<>();
        inputData.put("from", fromLang);
        inputData.put("to", toLang);
        inputData.put("input", input);

        long timestamp = System.currentTimeMillis() / 1000;
        String sign = createSign(timestamp, inputData);
        HttpHeaders headers = createHeaders(timestamp, sign);

        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(inputData, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);

        return responseEntity.getBody();
    }

    public String queryQuote(String fileId) throws IOException {
        String url = "https://fanyi-api.baidu.com/transapi/doctrans/query/quote";

        Map<String, Object> inputData = new HashMap<>();
        inputData.put("fileId", fileId);

        long timestamp = System.currentTimeMillis() / 1000;
        String sign = createSign(timestamp, inputData);
        HttpHeaders headers = createHeaders(timestamp, sign);

        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(inputData, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);

        return responseEntity.getBody();
    }

    public String createTransJob(String fromLang, String toLang, String extend, String fileName, String filePath, String output) throws IOException {
        String url = "https://fanyi-api.baidu.com/transapi/doctrans/createjob/trans";
        byte[] contentBytes = restTemplate.getForObject(filePath, byte[].class);
        String content = Base64.getEncoder().encodeToString(contentBytes);

        Map<String, Object> input = new HashMap<>();
        input.put("content", content);
        input.put("format", extend);
        input.put("filename", fileName);

        Map<String, Object> outputData = new HashMap<>();
        outputData.put("format", output);

        Map<String, Object> inputData = new HashMap<>();
        inputData.put("from", fromLang);
        inputData.put("to", toLang);
        inputData.put("input", input);
        inputData.put("output", outputData);

        long timestamp = System.currentTimeMillis() / 1000;
        String sign = createSign(timestamp, inputData);
        HttpHeaders headers = createHeaders(timestamp, sign);

        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(inputData, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);

        return responseEntity.getBody();
    }

    public String queryTrans(String requestId) {
        String url = "https://fanyi-api.baidu.com/transapi/doctrans/query/trans";

        Map<String, Object> inputData = new HashMap<>();
        inputData.put("requestId", requestId);

        long timestamp = System.currentTimeMillis() / 1000;
        String sign = createSign(timestamp, inputData);
        HttpHeaders headers = createHeaders(timestamp, sign);

        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(inputData, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);

        return responseEntity.getBody();
    }

    private String createSign(long timestamp, Map<String, Object> inputData) {
        String queryStr = JSON.toJSONString(inputData);
        String signStr = this.appid + timestamp + queryStr;
        byte[] hmacSha256Result = hmacSha256(this.seckey.getBytes(), signStr.getBytes());
        return Base64.getEncoder().encodeToString(hmacSha256Result);
    }

    private HttpHeaders createHeaders(long timestamp, String sign) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("X-Appid", appid);
        headers.set("X-Sign", sign);
        headers.set("X-Timestamp", String.valueOf(timestamp));
        return headers;
    }

    public static void main(String[] args) {
        String fromLang = "zh";
        String toLang = "en";
        String extend = "docx";
        String fileName = "test.docx";
        String filePath = "C:\\Users\\Administrator\\Desktop\\test.docx";
        String output = "docx";

        TranslateUtil translate = new TranslateUtil("20230625001723471", "tAUvXp7Op0HpmrDDUONo");

        try {
            // 创建报价服务
            String quoteRet = translate.createQuoteJob(fromLang, toLang, extend, fileName, filePath);
            System.out.println(quoteRet);
            JSONObject quoteRetJson = JSON.parseObject(quoteRet);
            String fileId = quoteRetJson.getJSONObject("data").getString("fileId");

            // 查询报价结果
            String queryQuoteRet = translate.queryQuote(fileId);
            System.out.println(queryQuoteRet);

            // 创建翻译服务
            String transRet = translate.createTransJob(fromLang, toLang, extend, fileName, filePath, output);
            System.out.println(transRet);
            JSONObject transRetJson = JSON.parseObject(transRet);
            String requestId = transRetJson.getJSONObject("data").getString("requestId");

            // 查询翻译结果
            String queryTransRet = translate.queryTrans(requestId);
            System.out.println(queryTransRet);
//http://bos.bj.baidubce.com/fanyidoc/api/20230718/20230625001723471/translate3.0_dst_c6b77d0971f6348f785a8c727979483a.docx?authorization=bce-auth-v1/a5299aaec62f4f88b0dad21f83e1c090/2023-07-18T14%3A31%3A35Z/15552000//aac59d99c91f7e046383c66ce62a7470d6aac24381d7cda876f531799d33310b
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}